package com.example.highclasscomponent.adapter;

import android.content.Context;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.example.highclasscomponent.pojo.GoodsInfo;

import java.util.ArrayList;
import java.util.List;

public class ImagePagerAdapter extends PagerAdapter {
    Context context;
    List<GoodsInfo> mGoodsList;
    private List<ImageView> mViewList=new ArrayList<>();

    public ImagePagerAdapter(Context context, List<GoodsInfo>goodsList) {
        this.context = context;
        this.mGoodsList = goodsList;
        //给每一个商品创建一个专用的图像视图
        for (GoodsInfo goodsInfo : mGoodsList) {
            ImageView view=new ImageView(context);
            view.setImageResource(goodsInfo.pic);
            view.setLayoutParams(new ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT));
            mViewList.add(view);
        }
    }

    @Override
    public int getCount() {
        return mGoodsList.size();
    }

    @Override
    //判断
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view==object;
    }

    @NonNull
    @Override
    //在这里实例化指定位置的页面并添加到容器中
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        ImageView view=mViewList.get(position);
        container.addView(view);
        Log.d("tang", "instantiateItem: 执行了一次初始化方法");
        return view;
    }

    @Override
    //页面翻转时始终保持container中只有2到3个页面实例
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        container.removeView(mViewList.get(position));//这里只是移除了，但是对象没有真正销毁
        Log.d("tang", "destroyItem: 执行了销毁方法");
    }

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        return mGoodsList.get(position).name;
    }
}
